﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SubSonic.DataProviders;

namespace TBlog.Models
{
    public class MysqlRepository : ITBlogRepository
    {
        // 
        //private TBlogEntities _entities = new TBlogEntities();

        //private MySqlStorage _entities = new MySqlStorage();
        

        //
        public IEnumerable<Category> ListCategory()
        {
            return _entities.Category.ToList();
        }

        //
        public Category CreateCategory(Category categoryToCreate)
        {
            _entities.AddToCategory(categoryToCreate);
            _entities.SaveChanges();
            return categoryToCreate;
        }

        //
        public Category GetCategory(int? categoryId)
        {
            return (from c in _entities.Category
                    where c.CategoryID == categoryId
                    select c).FirstOrDefault();
        }

        //
        public void DeleteCategory(Category categoryToDelete)
        {
            var originalCategoryToDelete = GetCategory(categoryToDelete.CategoryID);
            _entities.DeleteObject(originalCategoryToDelete);
            _entities.SaveChanges();
        }

        //
        public Category GetFirstCategory()
        {
            return _entities.Category.Include("Category").FirstOrDefault();
        }

        public IEnumerable<Post> ListPost()
        {
            return _entities.Post.ToList();
        }

        public IEnumerable<Post> GetPostCategory(int categoryId)
        {
            return _entities.Post.ToList();
        }

        public Post GetPost(int? postId)
        {
            return (from p in _entities.Post
                    where p.post_id == postId
                    select p).FirstOrDefault();
        }

        public Post GetFirstPost()
        {
            return _entities.Post.FirstOrDefault();
        }

        public Post CreatePost(Post postToCreate)
        {
            _entities.AddToPost(postToCreate);
            _entities.SaveChanges();
            return postToCreate;
        }

        public void DeletePost(Post postToDelete)
        {
            var originalPost = GetPost(postToDelete.post_id);
            _entities.DeleteObject(originalPost);
            _entities.SaveChanges();
        }
    }
}